# coding: utf-8
from pathlib import Path
from typing import Union

from PyQt6.QtCore import QFileInfo, Qt, QSize, pyqtSignal
from PyQt6.QtWidgets import QFileIconProvider, QWidget, QHBoxLayout
from qfluentwidgets import CardGroupWidget, TransparentToolButton, FluentIcon, GroupHeaderCardWidget, BodyLabel, \
    ComboBox


class FileToolbar(QWidget):
    clicked = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout(self)
        self.bodyLabel = BodyLabel(self)
        self.comboBox = ComboBox(self)
        self.closeButton = TransparentToolButton(FluentIcon.CLOSE, self)

        self.comboBox.addItems(['png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'bmp', 'heic', 'avif'])

        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.addWidget(self.bodyLabel)
        self.horizontalLayout.addWidget(self.comboBox)
        self.horizontalLayout.addWidget(self.closeButton)

        self.closeButton.clicked.connect(self.clicked)


class FileGroupCardWidget(GroupHeaderCardWidget):
    def _postInit(self):
        super()._postInit()
        self.files = []
        self.iconProvider = QFileIconProvider()
        self.groupLayout.setAlignment(Qt.AlignmentFlag.AlignTop)

    def addFile(self, file: Union[str, Path]) -> CardGroupWidget:
        """
        Add a group to the card widget.
        :param file:
        :return:
        """
        self.files.append(file)
        if isinstance(file, str):
            file = Path(file)
        btn = TransparentToolButton(FluentIcon.CLOSE, self)
        group = self.addGroup(
            self.iconProvider.icon(QFileInfo(str(file))),
            file.name,
            file.as_posix(),
            btn,
            stretch=0
        )
        btn.clicked.connect(lambda: self.removeGroup(group))
        return group

    def groupCount(self):
        return len(self.groupWidgets)

    def removeGroupIndex(self, index: int):
        group = self.groupWidgets[index]
        self.files.remove(group.content())
        self.groupWidgets.remove(group)
        self.groupLayout.removeWidget(group)
        group.deleteLater()

    def removeGroup(self, group: CardGroupWidget):
        self.removeGroupIndex(self.groupWidgets.index(group))

    def sizeHint(self):
        return QSize(500, 300)
